package com.itheima.service.impl;

import com.itheima.commons.pojo.CommonEntity;
import com.itheima.service.ElasticsearchIndexService;
import lombok.extern.slf4j.Slf4j; 
import org.elasticsearch.client.indices.CreateIndexRequest; 
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.springframework.beans.factory.annotation.Autowired; 
import java.util.Map;

/**
 * @program: itheima-technology-platform
 * @description: 增加索引的具体实现
 * @author: zhanghz001
 * @create: 2021-05-17 16:59
 **/
// @Service
@Slf4j
public class ZhzElasticsearchIndexServiceImpl implements ElasticsearchIndexService {
    @Autowired
    private RestHighLevelClient client;
    
    @Override
    public boolean addIndexAndMapping(CommonEntity commonEntity) throws Exception {
        //
        
        //创建索引请求
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(
                commonEntity.getIndexName()
        );
        //获取前端参数
        Map<String, Object> map = commonEntity.getMap();
        
        //循环settings和mapping
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Object value = entry.getValue();
            String key = entry.getKey();
            if ("map".equals(key)) {
                if (value instanceof Map && ((Map) value).size() > 0) {
                    createIndexRequest.settings((Map<String, Object>) value);
                }
            }
            if ("mapping".equals(key)) {
                if (value instanceof Map && ((Map) value).size() > 0) {
                    createIndexRequest.mapping(  (Map<String, Object>) value);
                    
                }
            }
        }
        
        //创建索引操作客户端
        IndicesClient indices = client.indices();
        
        //创建响应对象
        CreateIndexResponse response = indices.create(createIndexRequest, RequestOptions.DEFAULT);
        //得到响应结果
        return response.isAcknowledged();
        
    }
}
